package org.dromara.common.satoken.core.service

import cn.dev33.satoken.stp.StpInterface
import cn.hutool.core.collection.CollUtil
import org.dromara.common.core.domain.model.LoginUser
import org.dromara.common.core.enums.UserType
import org.dromara.common.core.exception.ServiceException
import org.dromara.common.core.service.PermissionService
import org.dromara.common.core.utils.SpringUtils
import org.dromara.common.core.utils.StringUtils
import org.dromara.common.satoken.utils.LoginHelper.getLoginUser

/**
 * sa-token 权限管理实现类
 *
 * @author Lion Li
 * @updater LikeYouDo
 */
open class SaPermissionImpl : StpInterface {
    /**
     * 获取菜单权限列表
     */
    override fun getPermissionList(loginId: Any?, loginType: String?): ArrayList<String>? {
        val loginUser = getLoginUser<LoginUser>()
        if (loginUser == null || loginUser.getLoginId() != loginId) {
            val permissionService: PermissionService? = getPermissionService()
            if (permissionService != null) {
                val list = StringUtils.splitList(loginId.toString(), ":")
                return ArrayList(permissionService.getMenuPermission(list[1].toLong()) as Collection<String>)
            } else {
                throw ServiceException("PermissionService 实现类不存在")
            }
        }
        val userType = UserType.getUserType(loginUser.userType)
        if (userType == UserType.APP_USER) {
            // 其他端 自行根据业务编写
        }
        return if (CollUtil.isNotEmpty(loginUser.menuPermission)) {
            // SYS_USER 默认返回权限
            ArrayList(loginUser.menuPermission as Collection<String>)
        } else {
            ArrayList()
        }
    }

    /**
     * 获取角色权限列表
     */
    override fun getRoleList(loginId: Any?, loginType: String?): ArrayList<String>? {
        val loginUser = getLoginUser<LoginUser>()
        if (loginUser == null || loginUser.getLoginId() != loginId) {
            val permissionService = getPermissionService()
            if (permissionService != null) {
                val list = StringUtils.splitList(loginId.toString(), ":")
                return ArrayList(permissionService.getRolePermission(list[1].toLong()) as Collection<String>)
            } else {
                throw ServiceException("PermissionService 实现类不存在")
            }
        }
        val userType = UserType.getUserType(loginUser.userType)
        if (userType == UserType.APP_USER) {
            // 其他端 自行根据业务编写
        }
        return if (CollUtil.isNotEmpty(loginUser.rolePermission)) {
            // SYS_USER 默认返回权限
            ArrayList(loginUser.rolePermission as Collection<String>)
        } else {
            ArrayList()
        }
    }

    private fun getPermissionService(): PermissionService? {
        return try {
            SpringUtils.getBean(PermissionService::class.java)
        } catch (e: Exception) {
            null
        }
    }
}
